package com.giscloud.limp.utils;

import com.deepoove.poi.XWPFTemplate;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ClassUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

public class DocUtils {

    public static void download(HttpServletResponse response, String newWordName, Map dataMap) {

        OutputStream toClient = null;
        try {
            ClassPathResource resource = new ClassPathResource("templates/word-template.docx");
            XWPFTemplate template = XWPFTemplate.compile(resource.getInputStream()).render(dataMap);
            // 清空response
            response.reset();
            // 设置response的Header
            newWordName = URLEncoder.encode(newWordName, "utf-8"); //这里要用URLEncoder转下才能正确显示中文名称
            response.addHeader("Content-Disposition", "attachment;filename=" + newWordName+"");
            response.setContentType("application/octet-stream");
            toClient = new BufferedOutputStream(response.getOutputStream());
            template.write(toClient);
            toClient.flush();
            toClient.close();
            template.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
